const jwt = require("jsonwebtoken");
// 首次连接触发
module.exports = (app) => {
  return async (ctx, next) => {
    const { socket } = ctx;
    
    // 获取前端传值
    const socketQuery = socket.handshake.query;
    console.log("messge：", socketQuery);
    await next();
    return
    if (!socketQuery) {
      throw new Error(401);
    }
    try {
      const data = jwt.verify(
        socketQuery.token,
        ctx.app.config.jwt.secret
      );
      // 连接上后给每个用户发一段文本
      if (socketQuery.clientType === "USER") {
        const robot = await ctx.model.Admininfo.findById(
          "66276a2e0d060000f90055b2"
        );
        const msg = {
          message: "请问有什么可以帮助到您吗",
          messageType: "001", //001:后台管理员，002：用户
          avatar: robot.logo,
          nickname: robot.name,
          _id: robot._id,
        };
        socket.emit("wxChat", msg);
      }
      //   根据角色加入不同房间
      if (socketQuery.clientType === "ADMIN") {
        socket.join("adminRoom");
      } else {
        socket.join(data.id);
      }

    } catch (err) {
      throw new Error(401);
    }
    await next();

  };
};
